import { Injectable, HttpException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { AuthEntity } from './entities/auth.entity';
import * as bcryptjs from 'bcryptjs';
import { JwtService } from '@nestjs/jwt';
import { RedisService } from '../redis/redis.service';

@Injectable()
export class AuthService {
  constructor(
    @InjectRepository(AuthEntity)
    private readonly authRepository: Repository<AuthEntity>,
    private readonly jwtService: JwtService,
    private readonly redisService: RedisService,
  ) {}

  // 登录
  async login(user: Partial<AuthEntity>) {
    const { username, password } = user;
    const authExist = await this.authRepository.findOne({
      where: { username },
    });
    if (!authExist) {
      throw new HttpException('用户名不存在', 400);
    }
    const isMatch = await bcryptjs.compare(password, authExist.password);
    if (!isMatch) {
      throw new HttpException('密码错误', 400);
    }
    // 查询redis中是否存在该用户
    const token = await this.redisService.get(authExist.id.toString());
    if (token) {
      return {
        mag: '登录成功',
        access_token: token,
      };
    } else {
      const token = this.jwtService.sign({
        id: authExist.id,
        username: authExist.username,
      });
      // 将token存入redis，有效期24小时
      await this.redisService.set(authExist.id.toString(), token, 60 * 60 * 24);
      return {
        mag: '登录成功',
        access_token: token,
      };
    }
  }
}
